package com.hao.tool.web.component.exception;

import com.hao.tool.common.entity.LayResponse;
import com.hao.tool.common.exception.ErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;

/**
 * 处理controller异常
 */
@ControllerAdvice
@Order(-1)
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory
            .getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler({ErrorPageException.class})
    public ModelAndView exception404(HttpServletResponse response, ErrorPageException exception) {
        logger.debug("Exception:{}", exception.getMessage());
        ModelAndView mv = new ModelAndView("common/404");
        mv.addObject("message", exception.getMessage());
        return mv;

    }

    @ResponseBody
    @ExceptionHandler(ErrorException.class)
    public LayResponse errorException(ErrorException e) {
        logger.error("err:", e);
        logger.debug("ErrorException:{}:{}", e.getErrCode(), e.getMessage());
        return new LayResponse().setCode(Integer.valueOf(e.getErrCode())).setMsg(e.getMessage());
    }


}
